package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.SwingConstants;
import javax.swing.WindowConstants;

import controller.Sistema;

/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class VentanaVenta extends javax.swing.JFrame {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private JLabel labelVenta;
	private JLabel labelCliente;
	private JLabel labelColumnas;
	private JButton botonAceptar;
	private JLabel labelMensajeStockProductos;
	private JScrollPane scrollProductos;
	private JList<ProductoView> listaProductos;
	private JLabel mensajeSeleccionMultiple;
	private JButton botonCancelar;
	private JLabel labelMensajeProductos;
	private JComboBox<ClienteView> comboClientes;
	private JOptionPane MensajeError;
	private JOptionPane MensajeTotal;
	protected static final Component IngresarCant = null;
	
	public VentanaVenta() {
		super();
		initGUI();
	}
	
	class MultiColumnCellRendererClienteView extends JPanel implements ListCellRenderer<ClienteView>{
		private static final long serialVersionUID = 1L;
		private final JLabel leftLabel = new JLabel();
		  private final JLabel rightLabel;
		  public MultiColumnCellRendererClienteView(int rightWidth) {
		    super(new BorderLayout());
		    this.setBorder(BorderFactory.createEmptyBorder(1,1,1,1));

		    leftLabel.setOpaque(false);
		    leftLabel.setBorder(BorderFactory.createEmptyBorder(0,2,0,0));

		    final Dimension dim = new Dimension(rightWidth, 0);
		    rightLabel = new JLabel() {
				private static final long serialVersionUID = 1L;

			@Override public Dimension getPreferredSize() {
		        return dim;
		      }
		    };
		    rightLabel.setOpaque(false);
		    rightLabel.setBorder(BorderFactory.createEmptyBorder(0,2,0,2));
		    rightLabel.setForeground(Color.GRAY);
		    rightLabel.setHorizontalAlignment(SwingConstants.RIGHT);

		    this.add(leftLabel);
		    this.add(rightLabel, BorderLayout.EAST);
		  }
		  @Override public Component getListCellRendererComponent(JList<? extends ClienteView> list, 
				  ClienteView value, int index, boolean isSelected, boolean cellHasFocus) {
			  
		    leftLabel.setText(String.valueOf(value.getDni()));
		    rightLabel.setText(value.getNombreCompleto());

		    leftLabel.setFont(list.getFont());
		    rightLabel.setFont(list.getFont());

		    if(index<0) {
		      leftLabel.setForeground(list.getForeground());
		      this.setOpaque(false);
		    }else{
		      leftLabel.setForeground(
		          isSelected?list.getSelectionForeground():list.getForeground());
		      this.setBackground(
		          isSelected?list.getSelectionBackground():list.getBackground());
		      this.setOpaque(true);
		    }
		    return this;
		  }
		  
		  @Override public Dimension getPreferredSize() {
		    Dimension d = super.getPreferredSize();
		    return new Dimension(0, d.height);
		  }		  
	}
	
	class CellRendererProductoView extends JLabel implements ListCellRenderer<ProductoView>{
		
		private static final long serialVersionUID = 1L;
		public CellRendererProductoView() {
			setOpaque(true);
		  }
		
		public Component getListCellRendererComponent(JList<? extends ProductoView> list, 
				ProductoView value, int index, boolean isSelected, boolean cellHasFocus) {
			  
			this.setText(value.getNombreLista());
		    if (isSelected) {
		        setBackground(list.getSelectionBackground());
		        setForeground(list.getSelectionForeground());
		      } else {
		        setBackground(list.getBackground());
		        setForeground(list.getForeground());
		      }
			return this;
		  }
	}
	
	private void initGUI() {
		try {
			this.setSize(400,500);
			setLocationRelativeTo(null);
			setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
			getContentPane().setLayout(null);
			{
				labelVenta = new JLabel();
				this.add(labelVenta);
				labelVenta.setText("Realizar Venta");
				labelVenta.setBounds(12, 12, 225, 28);
				labelVenta.setFont(new java.awt.Font("Segoe UI",0,22));
			}
			{
				labelCliente = new JLabel();
				this.add(labelCliente);
				labelCliente.setText("Cliente");
				labelCliente.setBounds(12, 79, 90, 16);
			}
			{
				Vector<ClienteView> clientes = Sistema.getInstance().obtenerVistaClientes();
				ComboBoxModel<ClienteView> listaClientesModel = new DefaultComboBoxModel<ClienteView>(clientes);
				ListCellRenderer<ClienteView> renderer = new MultiColumnCellRendererClienteView(130);
				comboClientes = new JComboBox<ClienteView>();
				this.add(comboClientes);
				comboClientes.setRenderer(renderer);
				comboClientes.setModel(listaClientesModel);
				comboClientes.setBounds(102, 76, 260, 23);
			}
			{
				labelColumnas = new JLabel();
				this.add(labelColumnas);
				labelColumnas.setText("DNI Apellido,Nombre");
				labelColumnas.setBounds(102, 54, 168, 16);
			}
			{
				labelMensajeProductos = new JLabel();
				this.add(labelMensajeProductos);
				labelMensajeProductos.setText("Seleccione los Productos de la venta:");
				labelMensajeProductos.setBounds(12, 134, 290, 16);
			}
			{
				mensajeSeleccionMultiple = new JLabel();
				this.add(mensajeSeleccionMultiple);
				mensajeSeleccionMultiple.setText("(mantener CTRL para seleccion multiple)");
				mensajeSeleccionMultiple.setBounds(12, 150, 296, 16);
			}
			{
				scrollProductos = new JScrollPane();
				this.add(scrollProductos);
				scrollProductos.setBounds(24, 185, 348, 164);
				{
					Vector<ProductoView> lista = Sistema.getInstance().obtenerVistaProductos();
					listaProductos = new JList<ProductoView>(lista);
					ListCellRenderer<ProductoView> renderer = new CellRendererProductoView();
					listaProductos.setCellRenderer(renderer);
					scrollProductos.setViewportView(listaProductos);
					listaProductos.setBounds(scrollProductos.getBounds());
					listaProductos.setPreferredSize(scrollProductos.getSize());
				}
			}
			{
				labelMensajeStockProductos = new JLabel();
				this.add(labelMensajeStockProductos);
				labelMensajeStockProductos.setText("Al Aceptar, se solicitaran las cantidades de cada Producto");
				labelMensajeStockProductos.setBounds(24, 361, 338, 16);
			}
			{
				botonCancelar = new JButton();
				getContentPane().add(botonCancelar);
				botonCancelar.setFont(new java.awt.Font("Segoe UI",0,18));
				botonCancelar.setBounds(71, 403, 110, 39);
				botonCancelar.setText("Cancelar");
				botonCancelar.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						close();
					}
				});
			}
			{
				botonAceptar = new JButton();
				this.add(botonAceptar);
				botonAceptar.setText("Aceptar");
				botonAceptar.setBounds(215, 403, 110, 39);
				botonAceptar.setFont(new java.awt.Font("Segoe UI",0,18));
				botonAceptar.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent evt) {
						try{
							List<ProductoView> seleccionados = listaProductos.getSelectedValuesList();
							Vector<ItemFacturaView> items = new Vector<ItemFacturaView>();
							for (ProductoView p: seleccionados){
								String cantidad;
								do{
									cantidad = JOptionPane.showInputDialog(IngresarCant, "Ingrese la cantidad de "+p.getNombre()+":");
									if (Integer.valueOf(cantidad) > p.getStock()){
										JOptionPane.showMessageDialog(MensajeError, "El valor no puede ser superior al stock disponible ("+p.getStock()+")","Error!",JOptionPane.ERROR_MESSAGE);
									}
								}while (Integer.valueOf(cantidad) > p.getStock());
								items.add(new ItemFacturaView(p,Integer.valueOf(cantidad)));
							}
							ClienteView cliente = (ClienteView) comboClientes.getSelectedItem();
							float total = Sistema.getInstance().insertarVenta(cliente.getDni(),items);
							JOptionPane.showMessageDialog(MensajeTotal, "El total de la venta es: "+total);
							setVisible(false);
						} 
						catch (Exception e) {
							e.printStackTrace();
						}
					}
				});
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void close(){
		this.dispose();
	}
}
